<?php

/**
 * Description of QuoteController
 *
 * @author NE
 */
class Backend_QuoteController extends RCMS_Core_BaseController {

	/**
	 * Data from shopping card config
	 * 
	 * @var array Name value pairs
	 */
	private $_shoppingConfig = array();

	/**
	 * Data from system config
	 *
	 * @var array Name value pairs
	 */
	private $_systemConfig = array();

    private $_locale = null;
	/**
	 * Initialization of the controller
	 * 
	 */
	public function init() {
        parent::init();
        $this->_checkLogin(array('preview', 'pdf'));
        $this->_model = new Backend_QuoteModel();
        $this->_shoppingConfig = $this->_model->selectShoppingConfig();
        if (null === $this->_locale){
            $this->_locale = new Zend_Locale(Zend_Locale::getLocaleToTerritory($this->_shoppingConfig['country']));
        }
		$this->_pdfPluginName = 'Toastedpdf';
    }

	/**
	 * Index action.
	 *
	 * Shows quote existing and new quotes list
	 */
	public function indexAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		
		//assigning variables
		//quote statuses
		$this->view->quotesAvstatuses = array(
			'new'  => 'New',
			'sent' => 'Sent',
			'sold' => 'Sold',
			'lost' => 'Lost'
		);
		//information about all quotes
		//$this->view->quotesData = $this->_getAllQuotes();
		$this->view->websiteUrl = $this->getWebsiteUrl();
		//$this->view->invoiceAllowed = RCMS_Object_PluginManager_PluginManager::checkPluginInstalled($this->_pdfPluginName);
		//for translator
		echo $this->_translator->processScreen($this->view->render($this->getViewScript()));
	}

	/**
	 * Edit action.
	 *
	 */
	public function editAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->getResponse()->setHeader('Cache-control', 'no-cache, no-store, max-age=0, must-revalidate', true);
        $this->getResponse()->setHeader('Expires', 'Mon, 01 Jan 1971 05:00:00 GMT', true);
        $this->getResponse()->setHeader('Pragma', 'no-cache', true);
		
        $localer = new DateLocaler($this->_locale);
        $this->view->registerHelper($localer, 'dateLocaler');
        
        $quoteId = (int) $this->getRequest()->getParam('qid');
		$generator = new RCMS_Object_Generator_Generator();
		$quote = new RCMS_Object_Quote_Quote($quoteId);

		if($quote->getId() > 0) {

			$userCart = new RCMS_Object_Shopping_ShoppingUserCart($quote->getShoppingCartId());
			$cartData = $userCart->getCartData();
            
			$subTotal = 0;
            $totalTax = 0;
			$taxDiscount = 0;
			
			//prepating tax labels
			$taxLabels = unserialize($this->_shoppingConfig['tax-labels']);
			//taxes counting
			$totalTax = $this->_countTaxes($userCart);
			if ( $totalTax && $totalTax['rule'] == false){
				$totalTax['rule'] = $this->_getTaxRule();
			}
			$currentTaxRule = array_merge(array('0'), $totalTax['rule']['tax']);			
			//counting discount for tax if neccessary
			$quoteDiscount = $quote->getDiscount();
			$quoteTaxGroup = $quote->getDiscountRate();
			
			if ($quoteTaxGroup !=0 && $quoteDiscount != 0 ) {
				$currentTaxRate = $totalTax['rule']['tax'][$quoteTaxGroup];
				if (is_numeric($currentTaxRate)) {
					$taxDiscount = $quoteDiscount - $quoteDiscount/(1 + $currentTaxRate / 100);
				}
			}
            if (is_array($cartData) && !empty ($cartData)){
				foreach($cartData as $key => $value) {
                    $subTotal += $value['price'] * $value['count'];
                }
			}			
           
			$this->view->quoteDetails = array(
				'quoteId'         => $quote->getId(),
				'hasPreview'      => ($quote->getContent() != ''),
				'quoteName'       => $quote->getName(),
				'quoteDate'       => strtotime($quote->getDate()),
				'quoteIntMsg'     => $quote->getInternalMessage(),
				'quoteDisclaimer' => $quote->getDisclaimer(),
                'quoteShipping'   => false,
                'quoteValidUntil' => $quote->getValidUntilDate()?strtotime($quote->getValidUntilDate()):strtotime($quote->getDate()),
			);
			if (!empty($this->_session->quotemailtext))
                $this->view->quoteDetails['mailToUser'] =  $this->_session->quotemailtext;
            else
                $this->view->quoteDetails['mailToUser'] = $this->_shoppingConfig['quote_email_body'];

            //shipping if it's enabled in config
            if ($this->_shoppingConfig['shipping_type'] != 'pickup'){
                $shipping = new RCMS_Object_Shipping_Shipping($quote->getShoppingCartId());
                $this->view->shippingData = $shipping->getShippingAddress();
                $this->view->quoteDetails['quoteShipping'] = $shipping->getShippingCost();
                $this->view->shippingMethod = $shipping->getShippingType();
            }

			$this->view->quoteDiscountTaxRate = $quoteTaxGroup;	// assigned tax rate for quote
			$this->view->quoteDiscount  = number_format($quoteDiscount,2,'.','');
			$this->view->subTotal		= $subTotal;				// sub total w/o tax and shipping
            $this->view->itemsTotalTax  = $totalTax['total'];		// clear tax w/o deducted discount (if it's even present)
            $this->view->taxDiscount	= $taxDiscount;				// tax discount
			$this->view->currentTaxRule	= $currentTaxRule;			// current set of taxes for given quote
			$this->view->taxLabels		= $taxLabels;				// tax labels for select box
			$this->view->cartData       = $cartData;				// quote content
			$this->view->shoppingConfig = $this->_shoppingConfig;
			$this->view->cartId         = $userCart->getId();
			$this->view->userMail       = $userCart->getEmail();
			$this->view->quoteEdit      = true;
            $this->view->lastEditedBy   = $quote->getLastEditedBy();
			
			
			$this->view->additionalUserData = array(
                'name'     => $userCart->getName(),
				'address1' => $userCart->getAddress1(),
				'address2' => $userCart->getAddress2(),
                'company'  => $userCart->getCompany(),
				'country'  => $userCart->getCountry(),
				'state'    => $userCart->getState(),
				'city'     => $userCart->getCity(),
				'zip'      => $userCart->getZip(),
				'phone'    => $userCart->getPhone()
			);
		} else {
			$this->_redirect($this->_config->website->website->defaultPage);
			return;
		}
		$this->view->websiteUrl = $this->getWebsiteUrl();
		$this->view->path = $this->_config->website->website->path;
        $this->view->datepickerFormat = $localer->datepickerDateFormat;
        $this->view->lang = $this->_locale->getLanguage();
		//for translator
		echo $this->_translator->processScreen($this->view->render($this->getViewScript()));
	}


	public function addnewAction()
    {

		$userCart = new RCMS_Object_Shopping_ShoppingUserCart();
		$timePostfix = date('Ymd-His');
		$userCart->setName(RCMS_Object_QuickConfig_QuickConfig::$temporaryNewQuoteName . $timePostfix);
		$userCart->setEmail('email@email.com');
		$userCart->setCountry($this->_shoppingConfig['country']);
		$cartId = $userCart->save();
        
		$quote = new RCMS_Object_Quote_Quote();
		$quote->setShoppingCartId($cartId);
		$quote->setName($userCart->getName());
        $quote->setStatus(RCMS_Object_Quote_Quote::Q_STATUS_NEW);
		$quote->setValidUntilDate(date('Y-m-d',time()+3*24*60*60));
        $user = unserialize($this->_session->currentUser)->getLogin();
        $quote->setLastEditedBy($user);
        $quoteId = $quote->save();
        
        if ($quoteId > 0) {
            $this->_redirect($this->getWebSiteUrl() . 'sys/backend_quote/edit/qid/' . $quoteId);
        } else {
            $this->_redirect($this->getWebSiteUrl());
        }
	}

	public function updatequoteoncreationAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost()) {
			$quoteId = (int) $this->getRequest()->getParam('qid');
            
			$name = $this->getRequest()->getParam('name');
			$quoteMail = $this->getRequest()->getParam('qMail');
			$quoteDate = $this->getRequest()->getParam('qDate');
            $quoteName = $this->getRequest()->getParam('qName');
            $quoteValidUntilDate = $this->getRequest()->getParam('qValidUntilDate');
			
			$quote = new RCMS_Object_Quote_Quote($quoteId);
			if (strtotime($quoteDate) != strtotime($quote->getDate()) ) {
				$quote->setDate( date('Y-m-d H:i:s', strtotime($quoteDate.' '.date('H:i:s')) ) );
			}
			$quoteValidUntilDate = strtotime($quoteValidUntilDate);
			if ($quoteValidUntilDate != false) {
				$quote->setValidUntilDate(date('Y-m-d H:i:s', $quoteValidUntilDate));
			} else {
				$quote->setValidUntilDate(date('Y-m-d H:i:s', time()+3*24*60*60));
			}
            
            $quote->setName($quoteName);
            $quote->save();

			$cart = new RCMS_Object_Shopping_ShoppingUserCart($quote->getShoppingCartId());
			$cart->setName(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('name')));
			$cart->setEmail(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('qMail')));
            $cart->setCompany(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('company')));
			$cart->setCountry(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('country')));
			$cart->setState(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('state')));
			$cart->setCity(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('city')));
			$cart->setZip(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('zip')));
			$cart->setAddress1(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('address1')));
			$cart->setAddress2(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('address2')));
			$cart->setPhone(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('phone')));
			$cart->save();

            if ($this->_shoppingConfig['shipping_type'] != 'pickup'){
                $this->_updateShipping($cart);
            }
            echo json_encode(array('error' => 0, 'msg' => 'success'));
		}
	}

	/**
	 * Update quote status. (AJAX calling in quote.js)
	 * 
	 */
	public function updatestatusAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
        
		if ($this->getRequest()->isPost()) {
			$quoteId = intval($this->getRequest()->getParam('qid'));
			$status = $this->getRequest()->getParam('status');
            $postmortem = $this->getRequest()->getParam('postmortem');

			$quote = new RCMS_Object_Quote_Quote($quoteId);
			$quote->setStatus($status);
            if ($postmortem) {
                $dislaimer = $quote->getDisclaimer();
                if ($dislaimer) {
                    $quote->setDisclaimer($disclaimer . ' ' . $postmortem);
                } else {
                    $quote->setDisclaimer($postmortem);
                }
            }
            $user = unserialize($this->_session->currentUser)->getLogin();
            $quote->setLastEditedBy($user);
			$result = $quote->save();

			if ($status == RCMS_Object_Quote_Quote::Q_STATUS_SOLD && $result) {
				$pluginName = 'Buyerarea';
				if (RCMS_Object_PluginManager_PluginManager::checkPluginInstalled($pluginName)) {
					try {
						$buyerarea = RCMS_Core_PluginFactory::createPlugin('Buyerarea', null, array('websiteUrl' => $this->getWebSiteUrl()));
						$buyerarea->logpayment(array('type'=>'quote', 'id'=>$quoteId));
					} catch (Exception $e) {
						$error = $e->getMessage();
					}
				}
			}

			if ($result) {
				echo json_encode(array('error' => 0, 'msg' => 'success'));
			} else {
				echo json_encode(array('error' => 1, 'msg' => 'Can\'t update quote status. Something went wrong'));
			}
		}
	}

	/**
	 * Delete quote. (AJAX calling in quote.js)
	 *
	 */
	public function deletequoteAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if ($this->getRequest()->isPost()) {
			$quoteId = intval($this->getRequest()->getParam('qid'));
			$quote = new RCMS_Object_Quote_Quote($quoteId);
			$userCart = new RCMS_Object_Shopping_ShoppingUserCart($quote->getShoppingCartId());
            $shipping = new RCMS_Object_Shipping_Shipping($userCart->getId());

			if ($quote->delete()) {
				$result = $userCart->delete();
				if ($result) {
                    $shipping->delete();
					echo json_encode(array('error' => 0, 'msg' => 'success'));
				} else {
					echo json_encode(array('error' => 1, 'msg' => 'Unable to remove user cart. Something went wrong'));
				}
			} else {
				echo json_encode(array('error' => 1, 'msg' => 'Unable to remove quote. Something went wrong'));
			}
		}
	}

	/**
	 * Generate quote action (AJAX calling in quote.js)
	 *
	 * Generate quote content for user and sends him an email with link to his quote preview
	 * 
	 */
	public function generateAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
        
		$generator = new RCMS_Object_Generator_Generator();
		$this->_systemConfig = $this->_model->selectSystemConfig();
        $loggedUser = unserialize($this->_session->currentUser);
		$user       = $loggedUser->getLogin();
        $userEmail  = $loggedUser->getEmail();
        unset($loggedUser);
		$quoteId = $this->getRequest()->getParam('qid');
		$quote = new RCMS_Object_Quote_Quote($quoteId);

        $emailToUser = RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('emailSend'));
        $discount    = RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('discount'));
        
		$userCart = new RCMS_Object_Shopping_ShoppingUserCart($quote->getShoppingCartId());
        $totalTax = $this->_countTaxes( $userCart, ($this->_shoppingConfig['show-price-ati']?true:false) );
		
		//quote tax rate part
		$shipping = new RCMS_Object_Shipping_Shipping($userCart->getId());
		$location = $shipping->getShippingAddress();
		$taxRate = $this->_getTaxRule(!empty($location) ? $location : null );
		$quoteRate = $quote->getDiscountRate();
		$totalTax['discount'] = $discount-$discount/(1+$taxRate['tax'][$quoteRate]/100);
        if ($emailToUser == 'true') {
            //text to put in email to user
            $userMailText = RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('usrMailText'));
            $userMailText = str_replace('{$name}', $userCart->getName(), $userMailText);
            $userMailText = str_replace('{$date}', date('Y-m-d'), $userMailText);
            $userMailText = str_replace('{$quote_url}', $this->getWebSiteUrl() . 'sys/backend_quote/preview/qid/' . $quoteId . '.' . md5($quoteId) . '.' . $quoteId, $userMailText);
            $userMailText = str_replace('{$website_url}', $this->getWebSiteUrl(), $userMailText);
            $userMailText = str_replace('{$logged_user}', '<a href="mailto:'.$userEmail.'">'.$user.'</a>', $userMailText);
            //sending email to user
            $mailSent = $this->_sendMailToUser(array('email'=>$userCart->getEmail(),'name'=>$userCart->getName()), $quoteId, $userMailText);
            //unset($userCart);
            //if mail sent, then we will generate quote content and set quote status as "sent"
            if($mailSent !== true) {
				echo json_encode(array('error' => 1, 'msg' => 'Can not send email. Quote was not generated'));
				return false;
            } else {
                //if mail sent, set quote status as sent
				$status = 'success';
				$quote->setStatus(RCMS_Object_Quote_Quote::Q_STATUS_SENT);
            }
        } elseif ($emailToUser == 'false') {
            $status = 'saved';
        }

		$quote->setDisclaimer(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('disclaimer')));
		$quote->setDiscount($discount);
		$quote->setContent($generator->generateQuoteContent($quote, $userCart, $totalTax));
		$quote->setInternalMessage(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('intMessage')));
		$quote->setLastEditedBy($user);
		$quote->save();
		
		echo json_encode(array('error' => 0, 'msg' => $status));
		
//        if ($this->_shoppingConfig['shipping_type'] != 'pickup'){
//            $this->_updateShipping($userCart);
//        }
        $this->_session->quotemailtext = trim($this->getRequest()->getParam('usrMailText'));
   
	}

	/**
	 * Show quote preview
	 */
	public function previewAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$preQuoteInfo = explode('.', $this->getRequest()->getParam('qid'));

		if ($preQuoteInfo[0] != $preQuoteInfo[2]) {
			echo '<h1>Ooops! Wrong quote?</h1>';
			return;
		}
		$quoteId = $preQuoteInfo[0];
		$quote = new RCMS_Object_Quote_Quote($quoteId);
		echo $this->_translator->processScreen($quote->getContent());
	}

	public function addproducttocartAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		$cartId = intval($this->getRequest()->getParam('cid'));
		$productId = intval($this->getRequest()->getParam('pid'));

		$userCart = new RCMS_Object_Shopping_ShoppingUserCart($cartId);
		$cartData = $userCart->getCartData();

        $updated = false;
        foreach ($cartData as &$item){
            if ($item['id'] == $productId && !isset($item['parent'])){
                $item['count']++;
                $updated = true;
                break;
            } 
        }
        if (!$updated) {
            $product = new RCMS_Object_Product_Product($productId);
            $cartData[] = array(
                'count' => 1,
                'photo' => $product->getPhoto(),
                'name'  => $product->getName(),
                'price' => $product->getPrice(),
                'note'  => '',
                'id'    => $product->getId(),
				'itemId'=> $product->getItemId()
            );
            if ($product->getFreebies() != ''){
                foreach (explode(',', $product->getFreebies()) as $id){
                    $freebie = new RCMS_Object_Product_Product($id);
                    $cartData[] = array(
                        'count' => 1,
                        'photo' => $freebie->getPhoto(),
                        'name'  => $freebie->getName(),
                        'price' => '0',
                        'note'  => '{%free%}',
                        'id'    => $freebie->getId(),
                        'parent'=> $productId,
						'itemId'=> $product->getItemId()
                    );
                    unset($freebie);
                }
            }
        }
		$userCart->setCartData($cartData);
		$result = $userCart->save();
		if($result) {
			echo json_encode(array('error' => 0, 'msg' => 'success'));
		}
		else {
			echo json_encode(array('error' => 1, 'msg' => 'Can not add product. Something went wrong'));
        }
	}

	/**
	 * Update user cart
	 * 
	 */
	public function updatecartAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$cartId = $this->getRequest()->getParam('qid');
		$userCart = new RCMS_Object_Shopping_ShoppingUserCart($cartId);
		$cartData = $userCart->getCartData();
		//item that should be removed
		//$toRemove = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('toRemove')));
		//items wich price should be updated
		$toUpdatePrice = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('toUpdPrice')));
		//items wich note should be updated
		$adminNotes = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('notes')));
		//items wich quantity should be updated
		$toUpdateQty = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('toUpdQty')));
        $quoteId = (int) $this->getRequest()->getParam('quoteId');
        $quote = new RCMS_Object_Quote_Quote($quoteId);
        if ($quote->getId() > 0) {
            $quote->setDisclaimer(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('disclaimer')));
            $quote->setInternalMessage(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('intMsgText')));
            $user = unserialize($this->_session->currentUser)->getLogin();
            $quote->setLastEditedBy($user);
            $quote->setDiscount(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('discount')));
            $quote->setDiscountRate(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('discountTaxRate')));
            $quote->save();
        }
		//update items price
		if(!empty ($toUpdatePrice)) {
			foreach ($toUpdatePrice as $priceItem) {	
				if(array_key_exists($priceItem->id, $cartData)) {
					$cartData[$priceItem->id]['price'] = $priceItem->value;
				}
			}
		}
		//update items qty
		if(!empty($toUpdateQty)) {
			foreach($toUpdateQty as $qtyItem) {
                $updId  = $qtyItem->id;
                $updQty = $qtyItem->value;
				if(array_key_exists($updId, $cartData)) {
					if($updQty == 0) {
                        // removing product with it freebies
                        foreach ($cartData as $key => $cartItem){
                            if (isset($cartItem['parent']) && $cartItem['parent']==$cartData[$updId]['id']){
                                unset($cartData[$key]);
                            }
                        }
                        unset ($cartData[$updId]);
						continue;
					}
					if($cartData[$updId]['count'] != $updQty) {
                        //updating quality
						$cartData[$updId]['count'] = $updQty;
                        foreach ($cartData as &$cartItem){
                            if (isset($cartItem['parent']) && $cartItem['parent']==$cartData[$updId]['id']){
                                $cartItem['count'] = $updQty;
                            }
                        }
					}
				}
			}
		}
		//update items notes
		if(!empty($adminNotes)) {
			foreach($adminNotes as $noteData) {
				if(array_key_exists($noteData->id, $cartData)) {
					$cartData[$noteData->id]['note'] = $noteData->value;
				}
			}
		}
		//saving cart
        $this->_session->quotemailtext = trim($this->getRequest()->getParam('mailUserText'));
        $userCart->setCartData($cartData);
		$userCart->save();
	}

	/**
	 * Getting data about quotes from database
	 * 
	 */
	private function _getAllQuotes() {
		$quotesData = $this->_model->selectAllQuotes();
		return $quotesData;
	}

	/**
	 * Sending mail to the user
	 *
	 */
	private function _sendMailToUser($mailTo, $quoteId, $mailText) {
		$mail = new RCMS_Object_Mailer_Mailer();
		if($this->_systemConfig['use_smtp']) {
			$mail->setSmtpConfig($this->_systemConfig['smtp_login'], $this->_systemConfig['smtp_password'], $this->_systemConfig['smtp_host']);
			$mail->setTransport(RCMS_Object_Mailer_Mailer::MAIL_TYPE_SMTP);
		}
		$mail->setFrom($this->_shoppingConfig['company']);
		$mail->setFromMail($this->_shoppingConfig['email']);
		$mail->setTo($mailTo['name']);
		$mail->setToMail($mailTo['email']);
		$mail->setSubject($this->_shoppingConfig['quote_email_subj']);
		$mail->setBody($mailText);
		return $mail->send();
	}
	
    /**
     * Internal function that updates shipping information
     * @param RCMS_Object_Shopping_ShoppingUserCart $userCart
     * @access private
     * @return void
     */
    private function _updateShipping(RCMS_Object_Shopping_ShoppingUserCart $userCart){
        $shipping = new RCMS_Object_Shipping_Shipping($userCart->getId());
        $shippingCost = $this->getRequest()->getParam('shipping');
		$shippingType = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('shippingType')));

        if ($this->getRequest()->getParam('shippingData') == '1'){
            $shippingData = array(
                'firstname' => $userCart->getName(),
                'lastname'  => '',
                'company'   => $userCart->getCompany(),
                'email'     => $userCart->getEmail(),
                'address1'  => $userCart->getAddress1(),
                'address2'  => $userCart->getAddress2(),
                'city'      => $userCart->getCity(),
                'state'     => $userCart->getState(),
                'zip'       => $userCart->getZip(),
                'country'   => $userCart->getCountry(),
                'phone'     => $userCart->getPhone()
            );
        } elseif ($this->getRequest()->getParam('shippingData') == '0'){
            return false;
        }else{
            $shippingData = (array)json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('shippingData')));
        }
        $shipping->setShippingAddress($shippingData);
        $shipping->setShippingService(array('type' => $shippingType, 'price' => $shippingCost));
        $shipping->saveShipping();

    }

    /**
     * Internal function recalculates taxes for taxable products in the cart
     * @param RCMS_Object_Shopping_ShoppingUserCart $userCart
     * @return string in number format xxx.xx
     * @access private
     */
    private function _countTaxes(RCMS_Object_Shopping_ShoppingUserCart $userCart, $detailed = false) {
        $cartData = $userCart->getCartData();
        $tax = array('total'=>0);
        
		$shipping = new RCMS_Object_Shipping_Shipping($userCart->getId());
        $shippingAddress = $shipping->getShippingAddress();
        unset($shipping);
        
        if (empty($shippingAddress) || $this->_shoppingConfig['shipping_type'] == 'pickup'){
            $shippingAddress = array (
                'country' => $userCart->getCountry(),
                'state' => $userCart->getState()
            );
        }
        $rule = $this->_getTaxRule($shippingAddress);
        $tax['rule'] = $rule;
		if ($rule !== false){
			foreach ($cartData as $key => $value) {
				if (!$value['price'] && array_key_exists($value['id'], $tax)) continue;
				$product = new RCMS_Object_Product_Product($value['id']);
				if ($product->getId() > 0  && $product->getTax()) {
					$taxPerItem = $value['price'] * ($rule['tax'][$product->getTax()] / 100);
					$tax['total'] += $value['count'] * $taxPerItem;
					$tax[$value['id']] = number_format($taxPerItem, 2, '.', '');
				}
				unset($product);
			}   
		}

		return $tax;
    }
	
	/**
	 * Method that return current tax rule
	 */
	private function _getTaxRule( $location = null ){
		if ($location === null ){
			if (isset($this->_shoppingConfig['default_tax_rule'])){
				$rule = unserialize($this->_shoppingConfig['default_tax_rule']);
				if (is_array($rule) && !empty ($rule)){
					return $rule;
				}
				unset($rule);
			}
			$location['country'] = $this->_shoppingConfig['country'];
			$location['state'] = $this->_shoppingConfig['state'];
		}
		
		$taxRules = unserialize($this->_shoppingConfig['tax-rules']);

        if ($taxRules) {
			foreach ($taxRules as $rule) {
				if ($this->_shoppingConfig['shipping_type'] == 'pickup') {
					if (in_array('pickup',$rule)) {
						return $rule;
					} else {
						continue;
					}
				}
				if (($rule['zone'] == $location['country'] && $location['state'] != '' && strpos($rule['subzone'],$location['state'])!==false)
					 || ((empty($location['state']) || $location['state'] == 'null') && strpos($rule['subzone'],$location['country']) !== false) ) {
					return $rule;
				}
			}
		}
        return false;
	}

	/**
	 * Method that interacts with selected pdf plugin to create pdf document for quote or cart
	 * @return application/pdf
	 * @return text/html
	 */
	public function pdfAction(){
		$this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
				
		$documentType	= $this->getRequest()->getParam('type');
		$id				= $this->getRequest()->getParam('id');
		$title			= $this->getRequest()->getParam('title');
		$paymendMethod	= $this->getRequest()->getParam('payment');
		$customId		= $this->getRequest()->getParam('customId');
		$shippingTaxRate= $this->getRequest()->getParam('shippingtaxrate', 0);

		switch ($documentType){
			case 'quote':
				$quote = new RCMS_Object_Quote_Quote($id);
				$cartId = $quote->getShoppingCartId();
				$date = $quote->getDate();
				$discount = $quote->getDiscount();
				$discountRate = $quote->getDiscountRate();
				unset($quote);
				break;
			case 'cart':
				$cartId = $id;
				$discount = 0;
				$discountRate = 0;
				$date = null;
				break;
			default:
				return false;
				break;
		}

		//preparing usercart content
		$usercart = new RCMS_Object_Shopping_ShoppingUserCart($cartId);
		$cartContent = $usercart->getCartData();
		$summary = array(
			'date' => strtotime($date != null ? $date : $usercart->getDate())
		);
		$taxes = $this->_countTaxes($usercart, true);

		$billingAddress = array(
			'firstname'	=> $usercart->getName(),
			'lastname'	=> '',
			'company'	=> $usercart->getCompany(),
			'email'		=> $usercart->getEmail(),
			'phone'		=> $usercart->getPhone(),
			'address1'	=> $usercart->getAddress1(),
			'address2'	=> $usercart->getAddress2(),
			'city'		=> $usercart->getCity(),
			'state'		=> $usercart->getState(),
			'zip'		=> $usercart->getZip(),
			'country'	=> $usercart->getCountry()
		);

		//preparing shipping data
		$shipping = new RCMS_Object_Shipping_Shipping($cartId);
		if ($shipping) {
			$shippingAddress = $shipping->getShippingAddress();
			$summary['shipping'] = $shipping->getShippingCost();
			$summary['shipping_type'] = $shipping->getShippingType();
		}

		//calculating total price
		$subtotal = 0;
		foreach ($cartContent as $item) {
			$subtotal += $item['price']*$item['count'] ;
		}

		$summary['subtotal']		= $subtotal;
		$summary['tax']				= $taxes['total'];
		$summary['discount']		= $discount;
		if ($discountRate != 0){
			$summary['discountTax']		= $discount * $taxes['rule']['tax'][$discountRate] / 100;
		} else {
			$summary['discountTax'] = 0;
		}
		$summary['total']			= $subtotal+$summary['tax']+$summary['shipping']-$discount;
		$summary['payment_method']	= $paymendMethod;
		$summary['title']			= ucfirst($title);
		$summary['id']				= !empty ($customId) ? $customId : $cartId;
		$summary['shippingTaxRate']	= floatval($shippingTaxRate);

		try {
			$plugin = RCMS_Core_PluginFactory::createPlugin($this->_pdfPluginName);
			$pdf = $plugin->run(
				array(
					'billingAddress'	=> $billingAddress,
					'shippingAddress'	=> $shippingAddress,
					'cart'				=> $cartContent,
					'taxes'				=> $taxes,
					'summary'			=> $summary
					)
				);
			if ($pdf) {
				$this->getResponse()->setHeader('Content-Type', 'application/pdf');
				$this->getResponse()->setHeader('Content-Disposition: ', 'attachment; filename="'.$title.'-'.$customId.'.pdf"');
				echo $pdf;
			}
		} catch (Exception $e) {
			echo $e->getMessage();
		}
		
	}

	/**
	 * Method returns json encoded data for quote management screen (AJAX)
	 * @return array json
	 */
	public function quotelistAction(){
		$this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

		if ($this->getRequest()->isPost()) {
			$invoiceAllowed = RCMS_Object_PluginManager_PluginManager::checkPluginInstalled($this->_pdfPluginName);

			$params = $this->getRequest()->getParams();
			$totalRecords = $this->_model->getQuotesCount();
			$filtered = false;
			$columns = array(
				0 => 'id',
				1 => 'name',
				2 => 'date',
				3 => 'status',
				4 => 'preview',
				5 => 'last_edited_by'
			);
			$columnsSearchable = array(0,1,2,3,5);
			
			// processing pagination
			if (isset ($params['iDisplayStart'])) {
				$limit = array('count'=>$params['iDisplayLength'],'offset'=>$params['iDisplayStart']);
			} else {
				$limit = false;
			}

			if (isset ($params['iSortingCols']) && $params['iSortingCols']) {
				$order = array();
				for ($i = 0; $i <= --$params['iSortingCols']; $i++){
					$order[] = $columns[$params['iSortCol_'.$i]].' '.strtoupper($params['sSortDir_'.$i]);
				}
			} else {
				$order = false;
			}

			if (isset ($params['sSearch']) && !empty ($params['sSearch'])){
				
				$conditions['search'] = $params['sSearch'];
//				$conditions['search_timestamp'] = Zend_Date::isDate($params['sSearch']) ? strtotime($params['sSearch']) : false;
				$conditions['fields'] = array();
				$cols = $params['iColumns'];
				for ($i = 0; $i < $cols; $i++ ) {
					if ( isset($params['bSearchable_'.$i]) && $params['bSearchable_'.$i] == true && in_array($i, $columnsSearchable) ) {
						array_push($conditions['fields'], $columns[$i]);
					}
				}
				$filtered = true;
			} else {
				$conditions = false;
			}

			$data = $this->_model->getQuotesList($conditions, $order, $limit);
			foreach ($data as &$quote) {
				if ($quote['status'] === RCMS_Object_Quote_Quote::Q_STATUS_SOLD && $invoiceAllowed) {
					$quote['invoice'] = true;
				} else {
					$quote['invoice'] = false;
				}
				if ($quote['preview'] == true) {
					$quote['preview'] = $this->getWebSiteUrl().'sys/backend_quote/preview/qid/'.$quote['id'].'.'.md5($quote['id']).'.'.$quote['id'];
				} else {
					$quote['preview'] = false;
				}
				$quote['date'] = date('d M Y H:i:s', strtotime($quote['date']));
			}
			echo json_encode(array('sEcho'=>  intval($params['sEcho']), "iTotalRecords" => $totalRecords, 'iTotalDisplayRecords' => $filtered?count($return):$totalRecords, 'aaData' => $data));
			return true;
		}
		
		echo json_encode(array());
		return false;
	}

	/**
	 * Method returns data for address search field on quote edit screen
	 * @return array json
	 */
	public function getquotedataAction(){
		$this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

		$term = $this->getRequest()->getParam('term');
		$qid  = $this->getRequest()->getParam('id');
		$data = null;
		if ($term){
			$data = $this->_model->getDataForQuote($term);
			if ($data && is_array($data)){
				foreach ($data as &$d){
					if (isset($d['shipping_address']) && strtolower($d['shipping_address']) != 'null') {
						$d['shipping_address'] = unserialize($d['shipping_address']);
					}
				}
			}
		}
		echo json_encode($data);
	}
}
